import 'dart:convert';
import 'package:manual/utils/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

class UserSharedPreferencesHelper {
  static const String _userInfoKey = "userInfo";

  // 初始化 SharedPreferences 并写入固定的 userInfo
  static Future<void> initializeUserInfo() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      // 定义固定的 userInfo
      Map<String, dynamic> userInfo = {
        "userId": 1003,
        "age": 13,
        "token": "00xx112453",
        "avatar": "lib/assets/images/common/icon.png",
      };
      // 将 userInfo 转换为 JSON 字符串并存储
      await prefs.setString(_userInfoKey, jsonEncode(userInfo));
      Logger.info("初始化 UserInfo 成功$userInfo", tag: "UserInfo");
    } catch (e) {
      Logger.error("初始化 UserInfo 时发生错误: $e" , tag: "UserInfo");
    }
  }

  /// 获取存储的 userInfo
  static Future<Map<String, dynamic>?> getUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    final userInfoString = prefs.getString(_userInfoKey);

    if (userInfoString != null) {
      return jsonDecode(userInfoString);
    }
    return null;
  }

  /// 更新 userInfo 的某个字段
  static Future<void> updateUserInfoField(String field, dynamic value) async {
    final prefs = await SharedPreferences.getInstance();
    final userInfoString = prefs.getString(_userInfoKey);

    if (userInfoString != null) {
      Map<String, dynamic> userInfo = jsonDecode(userInfoString);
      userInfo[field] = value; // 更新指定字段
      prefs.setString(_userInfoKey, jsonEncode(userInfo));
      print("UserInfo 更新成功：$userInfo");
    } else {
      Logger.error("userInfo更新失败", tag: "UserInfo Update");
    }
  }

  /// 清除 userInfo
  static Future<void> clearUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.remove(_userInfoKey);
    print("UserInfo 已清除！");
  }
}
